package com.oocl.chat.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import javax.swing.JOptionPane;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.chat.operate.impl.ReceiveOperateImpl;
import com.oocl.chat.pojo.Message;
import com.oocl.chat.ui.ChatFrame;
import com.oocl.chat.ui.LoginFrame;
import com.oocl.chat.ui.RegisterFrame;
import com.oocl.chat.util.Constans;
import com.oocl.thread.SendThread;

public class Client {
	public static Client client;
	private Socket socket;
	private BufferedWriter writer;
	private BufferedReader reader;
	private LoginFrame loginFrame;
	private RegisterFrame registerFrame;
	ReceiveOperateImpl roim = new ReceiveOperateImpl();
	
	
	public void start(){
		try {
			socket = new Socket("127.0.0.1",Constans.PORT);
//			loginFrame = new LoginFrame();
			registerFrame = new RegisterFrame();
			loginFrame = new LoginFrame();
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			receiveMessage();
		}catch (Exception e) {
			System.out.println("服务器未启动.....");
		}
	}
	public void receiveMessage(){
		Message message = null;
		ObjectMapper mapper = new ObjectMapper();
		String m = null;
		boolean flag = true;
		while(flag){
			try {
				if ((m = reader.readLine())!=null) {
					message = mapper.readValue(m, Message.class);
					receiveOperate(message);
				}
			} 
			 catch (IOException e) {
				System.out.print("服务器端下线！");
				flag=false;
			}
		}
	}
	
	private void receiveOperate(Message message){
		int type = message.getType();
		switch(type){
		case 0:
			roim.receiveChat(message);
			break;
		case 1:
			roim.receiveShake(message);
			break;
		case 2:
			if("0".equals(message.getContent())){
				registerFrame.alertErroInfo();
				break;
			}
			roim.receiveOnline(message);
			break;
		case 3:
			roim.receiveDownline(message);
			break;
		case 4:
			loginFrame.setVisible(false);
			roim.receiveNotifyList(message);
			break;
		case 6:
			if("0".equals(message.getContent())){
				registerFrame.alertErro();
			}else if("1".equals(message.getContent())){
				registerFrame.alertTrue();
				registerFrame.setVisible(false);
				loginFrame.setVisible(true);
			}
			break;
		case 10:
			roim.receiveServerOffline();
		}
	}
	public void sendMessage(Message message){
		try {
			new Thread(new SendThread(writer, message)).start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		client = new Client();
		client.start();
	}
}
